import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/home", // 根路径自动重定向到 /home
    },
    {
      path: "/home",
      name: "HomePage",
      component: () => import("@/views/HomePage.vue"),
    },
    {
      path: "/login",
      name: "LoginPage",
      component: () => import("@/views/LoginPage.vue"),
    },
    {
      path: "/detail/:name", // 使用 :name 作为动态参数
      name: "DetailPage",
      component: () => import("@/views/DetailPage.vue"),
    },
    {
      path: "/admin",
      name: "AdminPage",
      component: () => import("@/views/AdminPage.vue"),
      meta: { requiresAuth: true, role: "admin" }, //
    },
    {
      path: "/notice/:id",
      name: "NoticeDetail",
      component: () => import("@/views/NoticeDetail.vue"),
    },
    {
      path: "/huyaoguang",
      name: "HuYaoguangProfile",
      component: () => import("@/views/teachers/HuYaoguangProfile.vue"),
    },
    {
      path: "/zhangyanzi",
      name: "ZhangYanziProfile",
      component: () => import("@/views/teachers/ZhangYanziProfile.vue"),
    },
    {
      path: "/yangxiaonan",
      name: "YangXiaonanProfile",
      component: () => import("@/views/teachers/YangXiaonanProfile.vue"),
    },
    {
      path: "/wenjingqian",
      name: "WenJingQian",
      component: () => import("@/views/teachers/WenJingQian.vue"),
    },
  ],
});

// 全局守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");

  if (to.meta.requiresAuth && !token) {
    // 需要登录但没 token → 跳去登录页
    return next({ name: "LoginPage" });
  }

  next();
});

export default router;
